package com.nchu.learn.netty.resolver;

import com.nchu.learn.netty.model.Message;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author fujianjian
 * @project self-learning
 * @date 2020/1/16 11:27
 */
public final class MessageResolverFactory {
    private final static MessageResolverFactory FACTORY = new MessageResolverFactory();
    private final static List<Resolver> RESOLVER_LIST = new CopyOnWriteArrayList<>();

    public static MessageResolverFactory getInstance() {
        return FACTORY;
    }

    public void registerResolver(Resolver resolver) {
        RESOLVER_LIST.add(resolver);
    }

    public Resolver getResolver(Message message) {
        for (Resolver resolver : RESOLVER_LIST) {
            if (resolver.support(message)) {
                return resolver;
            }
        }

        throw new RuntimeException("cannot find resolver to handler message, the message Type:"
                + message.getMessageType().name());
    }
}
